<template>
    <TurnoutsList :turnouts="turnouts" @update:turnouts="onUpdateTurnouts"></TurnoutsList>
</template>
<script lang="ts" setup>
import { ref, onBeforeMount } from "vue";
import TurnoutsList from "../components/turnouts_config/TurnoutsList.vue"
import { Turnout } from "../models"
import { saveTurnouts, loadTurnouts } from "../api"
const turnouts = ref<Turnout[]>([
    {
        name: "",
        type: "left_hand_turnout",
        "magnets": [{ reversed: false, "index": 0, "ground_controller_name": "aaa" }],
        // "reversed": [],
        // "state": "left"
    }
])

onBeforeMount(async () => {
    const turnoutsData = await loadTurnouts()
    turnouts.value = turnoutsData
})

let saveTimeout: number = -1

const onUpdateTurnouts = (newTurnouts: Turnout[]) => {
    turnouts.value = newTurnouts
    if (saveTimeout) {
        clearTimeout(saveTimeout)
    }
    saveTimeout = setTimeout(() => {
        saveTurnouts(newTurnouts)
    }, 3000)
}
</script>
<style lang="css"></style>